package gui.drawers;

import java.awt.Graphics;
import java.awt.Point;

import dal.MapStruct;
import dal.object.Ball;
import gui.GameConstants;

@SuppressWarnings("serial")
public class BallDrawer extends Drawer{
	public double x, y;
	private double startX, startY;
	private int dx, dy;
	private ShadowDrawer shadow;
	public Ball ball;
	
	public BallDrawer(MapStruct ms, ShadowDrawer shadow) {
		this.setOpaque(false);
		this.setSize(ms.getSize());
		this.shadow = shadow;
		this.ball = new Ball();
		
		initBall(ms.getBallPosition());
	}
	
	/**
	 * @param p 
	 * 	initial position
	 * initializes the ball
	 */
	private void initBall(Point p){
		img = ball.getImage();
		this.dx = Ball.getDx();
		this.dy = Ball.getDy();
		
		if(p.x != 0 && p.y != 0){
			this.x = p.x;
			this.y = p.y;
		} else {
			this.x = dx;
			this.y = dy;
		}
		
		startX = x;
		startY = y;
	}
	
	/**
	 * moves the ball in the initial position when the level was started
	 */
	public void restart(){
		this.x = startX;
		this.y = startY;
		repaint();
	}
	
	/**
	 * @param j, i
	 * 	draws the ball in the middle of the indexed hexagon
	 */
	public void drawBall(int j, int i){
		this.x = GameConstants.getXbyIndex(j, i) + dx;
		this.y = GameConstants.getYbyIndex(i) + dy;
	}
	
	/**
	 * removes the ball shadow
	 */
	public void initSinking(){
		shadow.img = null;
	}
	
	/**
	 * @return
	 * 	returns false if the ball sunk
	 */
	public boolean sinkingBall(){
		img = ball.next();
		
		return img != null;
	}
	
	/**
	 * resets the ball
	 */
	public void resetBall(){
		img = ball.getImage();
		ball.reset();
		shadow.reset();
	}
	
	/**
	 * Moves the ball by x on x axis and by y on y axis. */
	public void moveBall(double x, double y){
		this.x += x;
		this.y += y;
	}
	
	/**
	 * @return
	 * 	the ball origo y
	 */
	public double getBallOrigoX(){
		return x + Ball.getOx();
	}
	
	/**
	 * @return
	 * 	the ball origo y
	 */
	public double getBallOrigoY(){
		return y + Ball.getOy();
	}
	
	// Drawing the ball
	protected void paintComponent(Graphics g) {
		shadow.drawShadow((int) x, (int) y);
		g.drawImage(img, (int) x, (int) y, null);
	}
	
	/**
	 * the same as repaint()
	 */
	public void repaintAll() {
		repaint();
	}

	/**
	 * destroys the ball
	 */
	public void destroyBall() {
		img = null;
	}
	
	/**
	 * sets the visibility both this and the shadow drawer
	 */
	public void setVisible(boolean vis){
		super.setVisible(vis);
		shadow.setVisible(vis);
	}
}